/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/** 
* GIMI Pingger
* A simple program which pings given target and logs the results to a file
* An example
 * ./gim_ping -s image_server
* @author Jari
* 
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "TGimiClient.h"



void runClient(TGimiClient *C){
	int ret;
	FILE *f;
	f = fopen("pingdata.txt","wt");
	FILE *fb = fopen("pingdata_bare.txt","wt");
	unsigned int t_start=ownTime_get_ms();
	while(1){
	    
	    ret = C->gim->ping(string(C->paramTargetName),500);
            if (ret < 0) {
              switch(ret){
                  case GIMI_TIMEOUT:
                      dPrint(2,"Ping timeout from %s",C->paramTargetName);
                      fprintf(f,"%u Ping TIMEOUT from %s\n",ownTime_get_ms_since(t_start),C->paramTargetName);
                      break;
                  case GIMI_INTERRUPT:
                      dPrint(2,"Ping to %s interrupted",C->paramTargetName);
                      fprintf(f,"%u Ping to %s interrupted\n",ownTime_get_ms_since(t_start),C->paramTargetName);
                      break;
                  case GIMI_ERROR:
                      dPrint(2,"Error while pinging to %s (invalid target or something)",C->paramTargetName);
                      fprintf(f,"%u Error while pinging to %s (invalid target or something)\n",ownTime_get_ms_since(t_start),C->paramTargetName);
                      break;
                  default:
                      dPrint(2,"API or something has changed, should not be here!!");
                      break;
              }
            } else {
              dPrint(2,"Ping returned after %dms from %s",ret, C->paramTargetName);
							fprintf(f,"%d ms - Ping returned OK from %s\n",ret,C->paramTargetName);
							fprintf(fb,"%d\n",ret,C->paramTargetName);
            }
	    fflush(f);
			fflush(fb);
	    ownSleep_ms(5);
	}

}


int main(int argc, char *argv[]){
	TGimiClient C;

	dPrint(2,"Entering the Parameterparser loop");
	C.parameterParser(argc,argv);
	dPrint(2,"Parameters Succesfully parsed");

	C.start_gimi();

	runClient(&C);
	
	return 0;
}
